const { OpenAI } = require('openai');
const express = require('express');
const cors = require('cors'); // Add this line
const openai = new OpenAI({
  baseURL: 'https://api.deepseek.com',
  apiKey: 'sk-b19ca2937e8444b595634c70ce7788a9'
});

const app = express();

// 使用
app.use(cors({
  origin: 'http://127.0.0.1:5500',//解决跨域问题 允许5500端口的请求
  methods: ['GET', 'POST', 'OPTIONS'],
  allowedHeaders: ['Content-Type']
}));

//解析前端发送的json数据
app.use(express.json());

//获取用户发送的message不应该使用get来获取，应该使用post来获取
app.post('/api/ask', async (req, res) => {
   try {
    const {message, historyMsg} = req.body;
    let completion = '';
    completion = await openai.chat.completions.create({
    messages: [{ role: "system", content: "你是一个专业的前端开发人员，使用中文回复用户问题" }, ...historyMsg, { role: 'user', content: message }],
    model: "deepseek-chat",
    });

    //返回ai的回复
    const aiAns = completion.choices[0].message.content
    res.json({
        success: true,
        response: aiAns
    })
   } catch (error) {
    console.log(error);
    res.json({
        success: false,
        response: error.message
    })
   }
})

app.listen(3000, () => {
    console.log('server start at port 3000');
})